<template>
  <div class="risk-container" v-title data-title="内控平台-风控矩阵">
    <a-back-top></a-back-top>
    <index-header headLine="内控平台-风控矩阵" backUrl="/internal/homepage"></index-header>
    <div class="content">
      <section>
          <a-form-model layout="inline" :model="templateForm" class="head">
        <a-form-model-item label="法人公司">
          <ComonTreeSelect
                  url="/lib/hteDict/getCompanyManageTree"
                  v-model="pagination.companyCode"
                  placeholder="请选择法人公司"
                  @valueChange="(value)=>{handleSearch(value,'company') } "
          ></ComonTreeSelect>
        </a-form-model-item>
        <a-form-model-item >
              <span slot="label">
                考核经营体
              </span>
          <ComonTreeSelect
                  ref="manageTree"
                  url="/lib/hteDict/getCompanyManageTree?dataType=2"
                  v-model="pagination.manageCode"
                  :param="{parentid:null}"
                  placeholder="请选择经营体"
                  @valueChange="handleSearch"
          ></ComonTreeSelect>
        </a-form-model-item>
        <a-form-model-item label="业务模块">
          <a-select v-model="pagination.businessModelId" placeholder="请选择" allowClear @change="handleSearch">
            <a-select-option v-for="item in dict.businessModeData" :value="item.id" :key="item.id">
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-button type="primary" html-type="submit" @click="handleSearch">搜索</a-button>
        <a-button @click="clearSearch">重置</a-button>
      </a-form-model>
          <div class="list-or-card">
            <div :class="{ active: typeFlag === 'det' }" @click="handleType(1)">
              <a-icon type="bars" />明细
            </div>
            <div :class="{ active: typeFlag === 'map' }" @click="handleType(2)">
              <a-icon type="apartment" />导图
            </div>
          </div>
        <div class="tab-box flex">
          <em>年度统计周期：{{statistic.currentYear - 1}}年11月1日至{{statistic.currentYear}}年10月31日</em>
          <div>
            <h4>风险点</h4>
            <ul>
              <li>当前风险点数量<p>{{statistic.riskTotal || 0}}</p></li>
              <li>年度问题风险点数量<p>{{statistic.yearRiskNum || 0}}</p></li>
            </ul>
          </div>
          <div>
            <h4>控制活动</h4>
            <ul>
              <li>当前控制活动数量<p>{{statistic.total || 0}}</p></li>
              <li>当前控制活动线上化率<p>{{statistic.onLineRate || 0}}%</p></li>
            </ul>
          </div>
          <div>
            <h4>问题整改</h4>
            <ul>
              <li>年度问题单数量<p>{{statistic.yearQuestionNum || 0}}</p></li>
              <li>年度问题单逾期率<p>{{statistic.yearOverTimeRate || 0}}%</p></li>
              <li>当前待完成问题单数量<p>{{statistic.completingNum || 0}}</p></li>
              <li>当前待完成问题单逾期率<p>{{statistic.completingOverTimeRate || 0}}%</p></li>
            </ul>
          </div>
        </div>
        <div class="div-box" align="right" >
          <a-button type="primary"  @click="handleShowExcel" >导入</a-button>
          <a-button type="primary"  @click="handleExporExcel" >导出风控矩阵</a-button>
          <a-button type="primary" >导出问题单/优化单</a-button>
        </div>
        <template>
          <MatrixDet :companyCode="pagination.companyCode" :manageCode="pagination.manageCode"
                     :businessModelId="pagination.businessModelId"  @pageChange="pageChange" ref="listRef" v-show="typeFlag =='det'" :total="pagination.total" @ok="getInitData"></MatrixDet>
          <MatrixMap :companyCode="pagination.companyCode" :manageCode="pagination.manageCode" :businessModelId="pagination.businessModelId"  ref="mapRef" v-show="typeFlag=='map'"></MatrixMap>
        </template>
      </section>
      <LuckSheetPaste   :title="'控制活动批量导入'" ref="luckSheetPaste" :columnsExcel="columnsExcel"  @handleOkExcel="handleOkExcel" ></LuckSheetPaste>
    </div>
  </div>
</template>
<script>
  import indexHeader from '@/views/components/indexHeader';
  import MatrixDet from '@/views/internal/matrix/matrixListDet';
  import MatrixMap from '@/views/internal/matrix/matrixListMap';
  import * as RequestHost from '@/api/env';
  import * as localStorage from '@/utils/localStorage';

  import LuckSheetPaste from '@/components/tools/LuckSheetPaste'
  import { getRiskAction  , postRiskAction} from '@/api/manage';
  import ComonTreeSelect from '@/components/tools/ComonTreeSelect';
  import {mapGetters} from "vuex";
  export default {
    name: 'InternalMatrix',
    components: {
      indexHeader,LuckSheetPaste , MatrixDet,MatrixMap ,ComonTreeSelect
    },
    data() {
      return {
        dict:{
          businessModeData:[],
          corporationModelData:[],
          manageTree:[]
        },
        pagination: {
          current: 1,
          pageSize: 1000,
          pageSizeOptions: ['10', '30', '50'],
          showQuickJumper: true,
          showSizeChanger: true,
          showTotal: (total, range) => {
            return range[0] + '-' + range[1] + ' 共' + total + '条';
          },
          total: 0,
          loading: false,
          companyCode:undefined ,
          manaCode:undefined ,
          businessModelId:undefined ,
          company: undefined, //法人公司
          status: undefined, // 业务模块
        },

        columnsExcel:[
          {
            title:'风险点编号' ,
            align:"center",
            dataIndex: 'riskNo'
          } ,
          {
            title:'法人公司' ,
            align:"center",
            dataIndex: 'companyName'
          },
          {
            title:'考核经营体' ,
            align:"center",
            dataIndex: 'manageName'
          },
          {
            title:'控制活动',
            align:"center",
            dataIndex: 'riskActivity'
          },
          {
            title:'检测点',
            align:"center",
            dataIndex: 'monitorPoint'
          },
          {
            title:'控制类型',
            align:"center",
            dataIndex: 'controlType'
          },
          {
            title:'是否线上控制',
            align:"center",
            dataIndex: 'isOnline'
          },
          {
            title:'控制系统' ,
            align:"center",
            dataIndex: 'controlSystem'
          } ,
          {
            title:'审批流名称' ,
            align:"center",
            dataIndex: 'approvalName'
          } ,
          {
            title:'关联制度编号' ,
            align:"center",
            dataIndex: 'associationInstitution'
          },
          {
            title:'控制属性' ,
            align:"center",
            dataIndex: 'controlAttributeName'
          },
        ],
        typeFlag: 'det',
        templateForm: {},
        writen: {},
        mapData:[],
        dataList:[],
        dataMap:[],
        toYear: (new Date()).getUTCFullYear,
        isTotalControl:false ,
        statistic:{
        },
        url:{
          list:'/incActivity/getAssessRisk',
          getMaxrixQueryParam:'/incActivity/getMaxrixQueryParam',
          export:'/incActivity/export',
          getMatrixDataList:'/incActivity/getMatrixDataList',
          getStatistic:'/incActivity/getStatisticData',
          dict: '/api/standardDigit/dict',
          delete:'/incBusinessProcess/delete/',
          addBatch:'/incActivity/addBatch',
          getBusinessModel:'/incBusinessProcessLevel/getBusinessModel',
          getCompanyList:'/lib/hteDict/getCompany',
          getManageTree:'/lib/hteDict/getManageTree',
        },
      };
    },
    computed:{
      ...mapGetters({
        getIncCurrentRole:'getIncCurrentRole'})
    },
    mounted() {
      this.initDict();
      this.getMaxrixQueryParam();
    },
    methods: {
      handleSearch(value , type){
        if (type=='company'){
          this.$set(this.pagination, 'manageCode', '');
          this.$refs.manageTree.param = { parentid: value };
          this.$refs.manageTree.fetchTree();
        }
        this.pagination.curren = 1;
        this.getStatisticData();
        this.getMatrixDataList()
        this.getInitData()
      },
      clearSearch(){
        this.pagination.companyCode = undefined
        this.pagination.manageCode = undefined
        this.pagination.businessModelId = undefined
        this.$set(this.pagination, 'isClear' , 1)
        this.handleSearch()
        this.getStatisticData();
      },
      handleExporExcel(){
        let url =
                RequestHost.baseUrl +
                '/riskchk/incActivity/export?&Authorization=' +
                encodeURI(encodeURI(localStorage.getStore('Authorization')));
              url += '&roleKey='+this.getIncCurrentRole.roleKey
        window.location.href = url;
      },
      handleShowExcel(){
        this.$refs.luckSheetPaste.showModalExcel();
      },
      handleOkExcel(data , excelVm){

        var vali = this.validate(data);
        var isOnlie = this.validateIsOnline(data);
        var controllType = this.validateControllType(data);
        var  controlAttribut = this.validateControlAttribut(data)
        if (isOnlie){
          this.$message.warning("是否线上控制字段只能填‘是’或者‘否’")
          excelVm.excelConfirmLoading = false;
        }
        else if (controllType){
          this.$message.warning("控制类型字段只能填‘预防型控制’或者‘检查型控制’")
          excelVm.excelConfirmLoading = false;
        }
        else if (controlAttribut){
          this.$message.warning("控制属性字段只能填‘法规要求’或者‘内控要求’")
          excelVm.excelConfirmLoading = false;
        }
        else {
          if (vali){
            postRiskAction(this.url.addBatch , data).then( res => {
              if (res.code == 0){
                excelVm.excelConfirmLoading = false;
                excelVm.afterClose();
                this.getInitData();
                this.getMatrixDataList();
                this.$message.success(res.msg)
              }
              else {
                this.$message.warning(res.msg)
                excelVm.excelConfirmLoading = false;
              }
            })
          }
          else {
            this.$message.error('请将信息完善后再保存')
            excelVm.excelConfirmLoading = false;
          }
        }
      },
      validateIsOnline(data){
        let flag =  data.every(item => {
          if ('是' === item.isOnline){
            this.$set(item , 'isOnlineCode' , 1);
          }
          if ('否' === item.isOnline){
            this.$set(item , 'isOnlineCode' , 0);
          }
          if (!['是','否'].includes(item.isOnline)){
            return true;
          }
        })
        return flag;
      },
      validateControllType(data){
        let flag = data.every( item =>{
          if ('预防型控制' == item.controlType){
            this.$set(item , 'controlTypeCode' , 1)
          }
          if ('检查型控制' == item.controlType){
            this.$set(item , 'controlTypeCode' , 2)
          }
          if (!['预防型控制','检查型控制'].includes(item.controlType)){
            return true;
          }

        })
        return flag;
      },
      validateControlAttribut(data){
        let flag = data.every( item =>{
          if ('法规要求' == item.controlAttributeName){
            this.$set(item , 'controlAttributeCode' , 1)
          }
          if ('内控要求' == item.controlAttributeName){
            this.$set(item , 'controlAttributeCode' , 2)
          }
          if (!['内控要求','法规要求'].includes(item.controlAttributeName)){
            return true;
          }
        })
        return flag;
      },
      getMaxrixQueryParam() {
        getRiskAction(this.url.getMaxrixQueryParam).then(res => {
          let result = res.data
          if (res.code == 0){
            this.$set(this.pagination , 'companyCode' , result.companyCode)
            this.$set(this.pagination , 'manageCode' , result.manageCode)
            this.$set(this.pagination , 'businessModelId' , result.businessModelId)

            this.getManageTree({parentid: result.companyCode})
            this.getMatrixDataList();
            this.getInitData();
            this.getStatisticData();
          }
        })
    },
      getStatisticData(){
        getRiskAction(this.url.getStatistic, {

          companyCode: this.pagination.companyCode,
          manageCode: this.pagination.manageCode,
          businessModelId: this.pagination.businessModelId,
          status: this.pagination.status ,
        }).then( res => {
          if (res.code == 0){
            this.statistic = res.data;
          }
        })
      },
      validate(data) {
        let result = data.every(item => {
          return item.riskActivity && item.riskActivity != ''
                  && item.controlType && item.controlType != ''
                  && item.isOnline && item.isOnline != ''
                  && item.riskNo && item.riskNo != ''
                  && item.companyName  && item.companyName != ''
                  && item.manageName && item.manageName != null

        })
        return result
      },
      pageChange(pagination){
        this.pagination.current = pagination.current
        this.pagination.pageSize = pagination.pageSize
        this.getInitData();
      },
      getMatrixDataList(){
        getRiskAction(this.url.getMatrixDataList ,{
          pageNo: this.pagination.current,
          pageSize: this.pagination.pageSize,
          keyword: this.pagination.keyword,
          companyCode: this.pagination.companyCode,
          manageCode: this.pagination.manageCode,
          businessModelId: this.pagination.businessModelId,
          status: this.pagination.status ,
          isClear:this.pagination.isClear
        } ).then( res => {

          debugger
          if (res.code == 0)
          {

            if (res.data != null && res.data != undefined){
              this.dataMap = res.data;
            }
            else {
              this.dataMap = [];
            }
            this.$refs.mapRef.setMapData(this.dataMap)
          }
        })
      },
      getManageTree(param = {} ){
        getRiskAction(this.url.getManageTree, param).then(res => {
          if (res.code == 0) {
            this.dict.manageTree = res.data;
            this.$forceUpdate()
          } else {
            this.$message.error('获取数据失败');
          }
        });
      },
      handleType(value){
        if (value == 1){
          this.typeFlag = 'det'
          this.$refs.listRef.setListData(this.dataList )
        }
        if (value == 2){
          this.typeFlag = 'map'
          this.$refs.mapRef.setMapData(this.dataMap)
        }
      },
      getInitData(current){
        if(current){
          this.pagination.current = current
        }
        this.pagination.loading = true;
        getRiskAction(this.url.list,{
          pageNo: this.pagination.current,
          pageSize: this.pagination.pageSize,
          keyword: this.pagination.keyword,
          companyCode: this.pagination.companyCode,
          manageCode: this.pagination.manageCode,
          isClear:this.pagination.isClear ,
          businessModelId: this.pagination.businessModelId,
          status: this.pagination.status}).then(res => {
          const result = res.data;
          if (res.code === 0) {
            this.dataList = result.records;
            this.$refs.listRef.setListData(this.dataList)
            this.pagination.total = result.total;
          } else {
            this.$message.error('查询列表失败');
          }
          this.pagination.loading = false;
        });
      },
      initDict(){
        const that = this;
        this.getManageTree()
        getRiskAction(this.url.getBusinessModel,{}).then(res => {
          if (res.code == 0) {
            that.dict.businessModeData = res.data;
          }
        })
        getRiskAction(this.url.getCompanyList, { }).then(res => {
          if (res.code == 0) {
            that.dict.corporationModelData = res.data;
          }
        })

        // that.initData();
      },
      // initData(){
      //   debugger
      //
      // },
      jugeInitData(companyCode ,manageCode , businessModelId){
        getRiskAction(this.url.list,{
          pageNo: this.pagination.current,
          pageSize: this.pagination.pageSize,
          companyCode: companyCode,
          manageCode: manageCode,
          isClear:this.pagination.isClear ,
          businessModelId: businessModelId,
          status: this.pagination.status}
          ).then(res => {
          const result = res.data;
          if (res.code === 0) {
            if (result.records.length > 0){
              return true;
            }
            else {
              return false
            }
          } else {
            return false;
          }
        });
      },
      handleCompanyChange(value){
        var parentid = null
        if(value){
          parentid = value
        }
        this.getManageTree({parentid:parentid})
        this.$set(this.pagination,'manageCode',undefined)
        this.handleSearch()
      },
    },
  };
</script>
<style lang="scss" scoped>
  @import '../main.scss';
  .list-or-card{padding-top: 5px;padding-right: 0;}
  .tab-box{border-top: 1px solid #e6e6e6;margin:15px 0 18px 0;padding-top:35px;position: relative;
    p{margin:0;padding: 0}
    >div{flex:1;border-radius: 4px;background-color: #539af8;box-shadow: 0 3px 6px rgba(0, 0, 0, 0.16);margin-right:18px;
      &:nth-child(2){background-color: #25CB92;}
      &:last-of-type{background-color: #A16BF5;margin-right: 0;}
    }
    h4{margin-bottom: 0;text-align: center;font-size: 16px;color: #f9f9f9;border-bottom: 1px solid #f7f7f7;font-weight: bold;padding: 8px 0;}
    ul{list-style: none;display: flex;justify-content: space-around;align-items: center;min-height: 100px;margin: 0;padding: 0 10px;
      li{color: #f9f9f9;font-size: 12px;padding: 10px;
        p{font-weight: bold;font-size: 18px;margin-top: 15px;text-align: center}
      }
    }
    >em{position: absolute;top:10px;right: 0;font-style: inherit;color: #5f5f5f;font-size: 13px;}
  }
  .div-box{
    margin-bottom: 20px;
  }
</style>
